#include "Player.h"
#include "common.h"
#include "chipFrame.h"
#include <time.h>

void callback(void *arg) {
	wxCommandEvent event(myEvent, chip_CallbackFunction);
	wxPostEvent(chippy, event);
}

bool elapsedCallback(void *arg) {
   return 1;	/// no loop
}

Player::Player() {
	currentSong = 0;
	currentIndex = 0;
	random = chip_YES;
	srand ( time(NULL) );
}

void Player::play(PlayList *list, int itemIndex, bool from_user) {
	if (!from_user && random == chip_YES) {

		itemIndex = rand() % playList->items.size() + 1;
	}
	currentIndex = itemIndex;
	playList = list;

	if (currentSong) {
	    ay_closesong(&currentSong);
	}


	currentSong = ay_initsong(list->items[itemIndex]->path.c_str(), 44100);
    #ifdef WINDOWS
    if (currentSong) ay_sethwnd(currentSong, (HWND) chippy->GetHWND());
    #endif

	if (currentSong) {
		ay_startsong(currentSong);
#warning "HERE!!!!!!!! it's mailed to BILL GATES!!!"
		ay_setelapsedcallback(currentSong, elapsedCallback, this);
		ay_setstoppedcallback(currentSong, callback, this);

#warning "next lines in TODO generate EVENT! no use gui in non gui thread"
		wxCommandEvent event(listBoxEvent, chip_NextTrack);
		wxPostEvent(chippy, event);
	} else printf("some shot /n \n");
}

void Player::playNext(bool from_user) {
	/// todo: mlia - its be work!
//	wxCommandEvent event(listBoxEvent, chip_NextTrack);
//	wxPostEvent(chippy, event);

	if (random == chip_YES || currentIndex + 1 < playList->items.size()) {
		play(playList, ++currentIndex, 0);
	} else {
	    if (currentIndex + 1 == playList->items.size()) currentIndex++;
		if (from_user) ay_closesong(&currentSong);
		 else ay_stopsong(&currentSong);
	}
}

void Player::playPrev() {
	if (random == chip_YES || currentIndex - 1 >= 0) {
		play(playList, --currentIndex, 1);
	} else {
	    if (currentIndex - 1 == -1) --currentIndex;
	    ay_closesong(&currentSong);
	}
}
/*
void Player::play(const char* path) {
}
*/
void Player::stop() {
}

